package com.gz.controller;

import com.gz.common.ProductService;
import com.gz.common.model.Category;
import com.gz.common.model.Product;
import com.gz.utils.Response;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

/**
 * Created by gongzhen on 2018/6/2.
 */
public class ProductController extends Controller {

    public void getTop() {
        int pageNum = getParaToInt("pageNum", 1);
        int pageSize = getParaToInt("pageSize", 3);
        Category category = ProductService.getService().getCategory("top");
        Page<Product> productPage = null;
        if (category != null) {
            String condition = " productCategoryId=" + category.getId();
            String orderBy = "sortNum asc";
            productPage = ProductService.getService().getProductPage(pageNum, pageSize, condition, orderBy);
        }
        renderJson(Response.responseJson(200, "成功", productPage));
    }

    public void getProductPage() {
        int pageNum = getParaToInt("pageNum", 1);
        int pageSize = getParaToInt("pageSize", 10);
        Category category = ProductService.getService().getCategory("normal");
        Page<Product> productPage = null;
        if (category != null) {
            String condition = " productCategoryId=" + category.getId();
            String orderBy = "sortNum asc";
            productPage = ProductService.getService().getProductPage(pageNum, pageSize, condition, orderBy);
            List<Product>productList=productPage.getList();
            if(productList!=null){
                for(Product product:productList){
                    if (product.getEndTime().before(new Date()) || product.getStartTime().after(new Date())) {
                        product.setIsMarketable(false);
                    }
                }
            }
        }
        renderJson(Response.responseJson(200, "成功", productPage));
    }

    public void getProduct() {
        Product product = ProductService.getService().getProduct(getParaToInt("id", 0));
        renderJson(Response.responseJson(200, "成功", product));
    }
}
